<template>
  <a-drawer
    :title="title"
    :maskClosable="true"
    :width="drawerWidth"
    placement="right"
    :closable="true"
    @close="handleCancel"
    :visible="visible"
    :body-style="{ paddingBottom: '80px' }">

    <template slot="title">
      <div style="width: 100%;">
        <span>{{ title }}</span>
        <span style="display:inline-block;width:calc(100% - 51px);padding-right:10px;text-align: right">
          <a-button @click="toggleScreen" icon="appstore" style="height:20px;width:20px;border:0px"></a-button>
        </span>
      </div>

    </template>

    <a-spin :spinning="confirmLoading">
      <a-form :form="form">

        <a-form-item label="项目名称" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入项目名称" v-decorator="[ 'name', validatorRules.name]"/>
        </a-form-item>

        <a-form-item label="项目类型" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-select style="width: 100%" v-decorator="[ 'projectType', validatorRules.projectType]" placeholder='请选择项目类型'>
            <a-select-option
              v-for="(role,roleindex) in projectTypeList"
              :key="roleindex.toString()"
              :value="role.value">
              {{ role.title }}
            </a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="项目规模" :labelCol="labelCol" :wrapperCol="wrapperCol" >
          <a-select  style="width: 100%" v-decorator="[ 'projectScale', validatorRules.projectScale]" placeholder='请选择项目规模'>
            <a-select-option
              v-for="(role,roleindex) in projectScaleList"
              :key="roleindex.toString()"
              :value="role.value">
              {{ role.title }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="电话" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入联系电话" v-decorator="[ 'phoneNumber',  validatorRules.phoneNumber]"/>
        </a-form-item>
        <a-form-item label="项目负责人" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入项目负责人" v-decorator="[ 'projectManager',  validatorRules.projectManager]"/>
        </a-form-item>

        <a-form-item label="项目地址" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入项目地址" v-decorator="[ 'address', validatorRules.address]"/>
        </a-form-item>

        <a-form-item label="行政区域编码" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入行政区域编码" v-decorator="[ 'regionCode', {}]"/>
        </a-form-item>

        <a-form-item label="项目经度" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入项目经度" v-decorator="[ 'longitude', {}]"/>
        </a-form-item>

        <a-form-item label="项目维度" :labelCol="labelCol" :wrapperCol="wrapperCol">
          <a-input placeholder="请输入项目维度" v-decorator="[ 'dimension', {}]"/>
        </a-form-item>

        <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol" label="状态">
          <a-radio-group name="radioGroup" v-decorator="['status',{initialValue: 1}]">
            <a-radio :value="1" >
              在用
            </a-radio>
            <a-radio :value="2">
              停用
            </a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-spin>
    <depart-window ref="departWindow" @ok="modalFormOk"></depart-window>

    <div class="drawer-bootom-button" style='margin-left: 100px' v-show="!disableSubmit">
      <a-button @click="handleSubmit" type="primary" :loading="confirmLoading" style='margin-right: 20px'>提交</a-button>
      <a-popconfirm title="确定放弃新增？" @confirm="handleCancel" okText="确定" cancelText="取消">
        <a-button style="margin-right: .8rem">取消</a-button>
      </a-popconfirm>

    </div>
  </a-drawer>
</template>

<script>
import pick from 'lodash.pick'
import Vue from 'vue'
// 引入搜索部门弹出框的组件
import departWindow from './DepartWindow'
import {ACCESS_TOKEN} from "@/store/mutation-types"
import {addProject, editProject, ajaxGetDictItems, duplicateCheck} from '@/api/api'


export default {
  name: "RoleModal",
  components: {
    departWindow,
  },
  data() {
    return {

      roleDisabled: false, //是否是角色维护调用该页面
      modalWidth: 800,
      drawerWidth: 700,
      modaltoggleFlag: true,
      confirmDirty: false,
      selectedDepartKeys: [], //保存用户选择部门id
      checkedDepartNames: [], // 保存部门的名称 =>title
      userId: "", //保存用户id
      projectId:"",//保存项目id
      disableSubmit: false,
      userDepartModel: {userId: '', departIdList: []}, // 保存SysUserDepart的用户部门中间表数据需要的对象
      dateFormat: "YYYY-MM-DD",
      validatorRules: {
        name: {
          rules: [{
            required: true, message: '请输入项目名称!'
          }, {
            validator: this.validateProjectname,
          }]
        },
        projectType:{
          rules:[{
            required:true,message:'请选择项目类型！'
          }]
        },
        projectScale:{
          rules:[{
            required:true,message:'请选择项目规模！'
          }]
        },
        projectManager:{
          rules:[{
            required:true,message:'请输入项目负责人！'
          }]
        },
        phoneNumber:{
          rules:[{
            required:true,message:'请输入负责人电话'
          },{
              validator: this.validatePhone,
          }]
        },
        address:{
          rules:[{
            required:true,message:'请输入项目所在地址'
          }]
        }
      },
      title: "操作",
      visible: false,
      model: {},
      roleList: [],
      projectScaleList: [],
      projectTypeList: [],
      selectedRole: '',
      labelCol: {
        xs: {span: 24},
        sm: {span: 5},
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16},
      },
      uploadLoading: false,
      confirmLoading: false,
      headers: {},
      form: this.$form.createForm(this),
      picUrl: "",
      url: {
        fileUpload: window._CONFIG['domianURL'] + "/sys/common/upload",
        imgerver: window._CONFIG['domianURL'] + "/sys/common/view",
        userWithDepart: "/sys/user/userDepartList", // 引入为指定用户查看部门信息需要的url
        userId: "/sys/user/generateUserId", // 引入生成添加用户情况下的url
        syncUserByUserName: "/process/extActProcess/doSyncUserByUserName",//同步用户到工作流

      },
    }
  },
  created() {
    const token = Vue.ls.get(ACCESS_TOKEN);
    this.headers = {"X-Access-Token": token}

  },
  computed: {
    uploadAction: function () {
      return this.url.fileUpload;
    }
  },
  methods: {

    //窗口最大化切换
    toggleScreen() {
      if (this.modaltoggleFlag) {
        this.modalWidth = window.innerWidth;
      } else {
        this.modalWidth = 800;
      }
      this.modaltoggleFlag = !this.modaltoggleFlag;
    },
      initProjectTypeList() {
          if (this.projectTypeList.length>0){
              return;
          }
          ajaxGetDictItems('project_type', null).then((res) => {
          if (res.success) {
            this.projectTypeList = res.result;
          } else {
            // console.log(res.message);
          }
        });
      },
      initProjectScaleList() {
          if (this.projectScaleList.length>0){
              return;
          }
          ajaxGetDictItems('project_scale', null).then((res) => {
              if (res.success) {
                  this.projectScaleList = res.result;
              } else {
              }
          });
      },

    refresh() {
      this.selectedDepartKeys = [];
      this.checkedDepartNames = [];
      this.userId = ""
    },
    add() {
      this.picUrl = "";
      this.refresh();
      this.edit({activitiSync: '1'});
    },
    edit(record) {
      // 调用此方法,根据屏幕宽度自适应调整抽屉的宽度
      this.resetScreenSize();
      let that = this;
      that.initProjectTypeList();
      that.initProjectScaleList();
      that.form.resetFields();
      that.projectId = record.id;
      that.visible = true;
      that.model = Object.assign({}, record);
      if (record.id){
      this.model.projectType = this.model.projectType + "";
      this.model.projectScale = this.model.projectScale + "";
      }
      that.$nextTick(() => {
          that.form.setFieldsValue(pick(this.model, 'name', 'projectNum', 'projectType', 'projectScale','phoneNumber',  'projectManager', 'address','regionCode', 'longitude', 'dimension', 'status','activitiSync'))
      });
    },
    close() {
      this.$emit('close');
      this.visible = false;
      this.disableSubmit = false;
      this.selectedRole = '';
      this.userDepartModel = {userId: '', departIdList: []};
      this.checkedDepartNames = [];
      //this.checkedDepartNameString = '';
      //this.checkedDepartKeys = [];
      this.selectedDepartKeys = [];
    },

    handleSubmit() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let formData = Object.assign(this.model, values);
          let obj;
          if (!this.model.id) {
            formData.id = this.projectId;
            obj = addProject(formData);
          } else {
            obj = editProject(formData);
          }
          obj.then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
            that.checkedDepartNames = [];
            that.userDepartModel.departIdList = {userId: '', departIdList: []};

            that.close();
          })

        }
      })
    },
    handleCancel() {
      this.close()
    },

    validatePhone(rule, value, callback) {
      if (!value) {
        callback()
      } else {
        if (new RegExp(/^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57]|166)[0-9]{8}$/).test(value)) {
          var params = {
            tableName: 'sys_user',
            fieldName: 'phone',
            fieldVal: value,
            dataId: this.userId
          };
          callback()
        } else {
          callback("请输入正确格式的手机号码!");
        }
      }
    },
    validateProjectname(rule, value, callback) {
      var params = {
        tableName: 't_project',
        fieldName: 'name',
        fieldVal: value,
        dataId: this.projectId
      };
      duplicateCheck(params).then((res) => {
        if (res.success) {
          callback()
        } else {
          callback("项目名已存在!")
        }
      })
    },
    modalFormOk(formData) {
      this.checkedDepartNames = [];
      this.selectedDepartKeys = [];
      //this.checkedDepartNameString = '';
      this.userId = formData.userId;
      this.userDepartModel.userId = formData.userId;
      for (let i = 0; i < formData.departIdList.length; i++) {
        this.selectedDepartKeys.push(formData.departIdList[i].key);
        this.checkedDepartNames.push(formData.departIdList[i].title);
        //this.checkedDepartNameString = this.checkedDepartNames.join(",");
      }
      this.userDepartModel.departIdList = this.selectedDepartKeys;
      //this.checkedDepartKeys = this.selectedDepartKeys  //更新当前的选择keys
    },
    // 根据屏幕变化,设置抽屉尺寸
    resetScreenSize() {
      let screenWidth = document.body.clientWidth;
      if (screenWidth < 500) {
        this.drawerWidth = screenWidth;
      } else {
        this.drawerWidth = 700;
      }
    },
  }
}
</script>

